from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from glowdrop.notes.models import Note, Comment
from django.contrib.auth.decorators import login_required
from django.utils.translation import ugettext as _
import simplejson
import settings
from glowdrop.utils import login_required_api, adjust_avatar, auth_required_api
from django.utils.timesince import timesince

def notes(request):
    """in fact, this is not WEB SERVICE, since it rely upon the user's session.
    this function returns all the notes or notes from a person sorted by time 
    DECRIMENTALLY.
    * May contain a parameter "username", denotes the notes's publisher. If it is
        not there, then all the notes is returned
    * Must contain a parameter 'count', denotes to get how many notes. 
    * May contain a parameter "max_id", when it is there, means retrieve the notes
        with id less than "max_id"(remember that the less the id of a note is, the
        earlier it is posted), when it is not there, retrieve the latest notes
    """
    assert request.GET.has_key('count'), "request must have parameter 'count' set"
    cnt = int(request.GET['count'])
    try:
        max_id = request.GET['max_id']
        notes = Note.objects.order_by("-id").filter(id__lt=max_id)
    except KeyError:           # not has key max_id 
        notes = Note.objects.order_by("-id")

    try:
        notes = notes.filter(author__username=request.GET['username'])
    except KeyError:       # not has key 'username' 
        pass
    notes = notes.all()[:cnt]

    r = []
    for i in notes:
        avatar = i.author.get_profile().image_link
        if not avatar:
            avatar = settings.DEFAULT_AVATAR_LINK
        else:
            avatar = avatar.url
        d = {'id': i.id, 'content': i.content, 'avatar': avatar, 'author': i.author.username, 
                'pub_date': timesince(i.pub_date), 
                'comments_cnt': Comment.objects.filter(note=i).count()}
        r.append(d)
    return HttpResponse(content=simplejson.dumps(r), status=200) 

@auth_required_api
def post_note(request):
    """ post a note, and return note itself
    """
    assert request.method == "POST"
    content = request.POST['content'].strip()
    if not content:
        return HttpResponse(content=_("note can't be empty"), status=404)
    note = Note()
    note.content = content
    note.author = request.user
    note.save()
    return note


def note(request):
    """in fact, this is not WEB SERVICE, since it rely upon the session
    if the request's method is POST, then the new posted note is returned in AN
    ARRAY
    """
    if request.method == 'POST':
        note = post_note(request)
        avatar = adjust_avatar(note.author.get_profile().image_link)
        ret = [{'id': note.id, 'content': note.content, 'avatar': avatar, 
                'author': note.author.username, 'pub_date': timesince(note.pub_date),
                'comments_cnt': 0}]
        return HttpResponse(content=simplejson.dumps(ret), status=200)

@auth_required_api
def me_fellows_notes(request):
    """in fact, this is not WEB SERVICE, since it rely upon the user's session.
    this function returns the notes posted from "me and my fellows" sorted by time
    DECRIMENTALLY.
    * Must contain a parameter 'count', denotes to get how many notes. 
    * May contain a parameter "max_id", when it is there, means retrieve the notes
        with id less than "max_id"(remember that the less the id of a note is, the
        earlier it is posted), when it is not there, retrieve the latest notes
    """
    assert request.GET.has_key('count'), "request must have parameter 'count' set"
    cnt = int(request.GET['count'])
    try:
        max_id = request.GET['max_id']
        notes = request.user.note_set.order_by("-id").filter(id__lt=max_id)[:cnt]
    except KeyError:
        notes = request.user.note_set.order_by("-id")[:cnt];
    r = []
    for i in notes:
        avatar = i.author.get_profile().image_link
        if not avatar:
            avatar = settings.DEFAULT_AVATAR_LINK
        else:
            avatar = avatar.url
        d = {'id': i.id, 'content': i.content, 'avatar': avatar, 'author': i.author.username, 
                'pub_date': str(i.pub_date), 
                'comments_cnt': Comment.objects.filter(note=i).count()}
        r.append(d)
    return HttpResponse(content=simplejson.dumps(r), status=200) 

@login_required_api
def post_comment(request):
    """ this method is not a web service actually
    """
    assert request.method == "POST"
    comment = Comment()
    comment.author = request.user
    comment.content = request.POST['content']
    comment.note = Note.objects.get(id=request.POST['note_id'])
    comment.save()
    avatar = comment.author.get_profile().image_link
    if not avatar:
        avatar = settings.DEFAULT_AVATAR_LINK
    else:
        avatar = avatar.url

    return HttpResponse(simplejson.dumps([{'content': comment.content, 'pub_date': str(comment.pub_date),
        'author': comment.author.username, 'avatar': avatar}, ]))

def comment(request):
    if request.method == "POST":
        ret = post_comment(request)
    else:                      # get 
        comments = Comment.objects.filter(note=Note.objects.get(id=request.GET['note_id']))
        ret = []
        for i in comments:
            comment = {'content': i.content, 'pub_date': timesince(i.pub_date), 
                    'author': i.author.username, 
                    'avatar': adjust_avatar(i.author.get_profile().image_link)}
            ret.append(comment)
        ret = HttpResponse(simplejson.dumps(ret))
    return ret
